package com.cy.web.filter;

import java.io.IOException;
import java.util.LinkedHashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;

import com.cy.service.system.BlogrollService;
import com.cy.service.system.IndexNaviService;

/**
 * 系统初始过滤器
 * @author CY
 *
 */
@WebFilter
public class SystemInit implements Filter {

	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//获取web的ServletContext对象
		ServletContext servletContext = filterConfig.getServletContext();
		//获取Spring的application容器
		ApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();
		// 将超链接存放到application中
		loadBlogroll(servletContext, applicationContext);
		// 加载首页链接数据
		loadIndexNavi(servletContext, applicationContext);
	}

	/**
	 * 加载首页链接数据
	 * @param servletContext
	 * @param applicationContext
	 */
	private void loadIndexNavi(ServletContext servletContext,
			ApplicationContext applicationContext) {
		IndexNaviService indexNaviService = (IndexNaviService) applicationContext.getBean("indexNaviServiceBean");
		String where = "o.indexNavi_visible = true and o.indexNavi_more = false";
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("indexNavi_order", "asc");
		servletContext.setAttribute("indexNavis", indexNaviService.getScrollData(-1,-1,where,null,orderby));
		//添加更多里面的导航链接
		where = "o.indexNavi_visible = true and o.indexNavi_more = true";
		servletContext.setAttribute("indexNavis_more", indexNaviService.getScrollData(-1,-1,where,null,orderby));
		
	}

	/**
	 * 系统运行时加载友情链接数据
	 * @param servletContext
	 * @param applicationContext
	 */
	private void loadBlogroll(ServletContext servletContext,
			ApplicationContext applicationContext) {
		BlogrollService blogrollService = (BlogrollService) applicationContext.getBean("blogrollServiceBean");
		String where = "o.blogrool_visible = true";
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("blogrool_order", "asc");
		servletContext.setAttribute("blogrolls", blogrollService.getScrollData(-1,-1,where,null,orderby));
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

}
